package com.k.kc.util.thread.demo1;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class Test {
    public static void main(String[] args) {
        testError();
    }

    private static void testError() {
        CompletableFuture<Void> v1 = CompletableFuture.runAsync(()->{
            System.out.println(1/0);
            System.out.println("v1 work");
        });
        System.out.println("v2 go");
        CompletableFuture<Void> v2 = CompletableFuture.runAsync(()->{
            System.out.println("v2 work");

        });

        try {
            CompletableFuture.allOf(v1,v2).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static void testThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread 方式的线程");
            }
        }).start();
    }
    private static void testExecutorService() throws ExecutionException, InterruptedException {
        ExecutorService pool= BusinessThreadPool.getThreadPool();
        ExecutorService pool2 = BusinessThreadPool2.getThreadPoolExecutor();
        // 无返回值的异步任务
        pool.execute(()->{
            System.out.println("xx");
        });
        // 返回结果的异步任务
        Future<String> future = pool.submit(()->{
            return "hello";
        });
        System.out.println(future.get());
    }
    private static void testCompletableFuture(){
        System.out.println(Thread.currentThread()+" testCompletableFuture()");
        CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread()+"-"+"Executing Task...");
            return "Task Completed";
        }).thenApply(result -> {
            System.out.println(Thread.currentThread()+"-"+"Processing Result: " + result);
            return result.length();
        }).thenAccept(resultLength -> {
            System.out.println(Thread.currentThread()+"-"+"Result Length: " + resultLength);
        });

        try {
            String r = CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread()+"-"+"Executing Task...");
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "4s后返回结果";
            }).get(6, TimeUnit.SECONDS);
            System.out.println(r);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        // 主线程等待一段时间，确保异步任务完成
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
